package com.test.mchelepesa.util_rice.data

import android.content.Context
import com.test.mchelepesa.util_rice.data.bean.BatteryInfo_rice
import com.test.mchelepesa.util_rice.data.bean.DeviceInfo_rice
import com.test.mchelepesa.util_rice.data.bean.HardwareInfo_rice
import com.test.mchelepesa.util_rice.data.bean.MsgInfo_rice
import com.test.mchelepesa.util_rice.data.bean.WifiInfo_rice
import com.test.mchelepesa.util_rice.data.bean.StorageInfo_rice
import com.google.gson.Gson

class DeviceUtil_rice(val context: Context, val product: String, val token: String) {

    private fun fetchCommon(path: String, fetchData: () -> String?): String? {
        if (!checkParams(path)) return null
        return fetchData()
    }

    private fun fetchCommonWithParams(
        path: String,
        key: String,
        fetchData: () -> String?
    ): String? {
        if (!checkParams(path)) return null
        val data = fetchData() ?: return null
        val params = commonParams(path).apply { put(key, data) }
        return Gson().toJson(params).trim()

        // TODO: 加密操作
        // ASAesUtil.encryptDefault(result)
    }

    private fun checkParams(path: String) = listOf(product, token, path).all { it.isNotBlank() }

    private fun commonParams(path: String) = hashMapOf<String, Any>(
        "path" to path.replace("/", ""),
        "token" to token,
        "product" to product
    )

    fun fetchDevice(path: String) = fetchCommon(path) {
        DeviceInfo_rice(context, product, token, path).fetch()
    }

    fun fetchMsg(path: String) = fetchCommon(path) {
        MsgInfo_rice(context, product, token, path).fetch()
    }

    fun fetchHardware(path: String) = fetchCommonWithParams(path, "deviceHardwareGzip") {
        HardwareInfo_rice(context).fetch()
    }

    fun fetchBattery(path: String, onResult: (String?) -> Unit) {
        BatteryInfo_rice(context = context, onResult = { bd ->
            val result = fetchCommonWithParams(path, "deviceBatteryGzip") { bd }
            onResult.invoke(result)
        }).start()
    }

    fun fetchRam(path: String) = fetchCommonWithParams(path, "deviceStorageGzip") {
        StorageInfo_rice(context).fetch()
    }

    fun fetchWifi(path: String) = fetchCommonWithParams(path,  "deviceWifiGzip") {
        WifiInfo_rice(context).fetch()
    }

}